package com.chenyanqing.model.two.service;

import com.chenyanqing.model.two.annotation.Autowired;
import com.chenyanqing.model.two.annotation.Service;
import com.chenyanqing.model.two.annotation.TimeLog;
import com.chenyanqing.model.two.annotation.Transactional;
import com.chenyanqing.model.two.dao.impl.UserDaoImpl;
import com.chenyanqing.model.two.factory.TimeLogAnnotationProxyFactory;
import com.chenyanqing.model.two.model.User;
import com.chenyanqing.model.two.utils.TransactionalManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;


@Service("myPayService")  //自定义service注解
public class PayServiceImpl  implements  PayService{

    private static Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);


    @Autowired
    private UserDaoImpl userDao;


    /**
     * 转账逻辑
     * @param fromUserId  id=1   1000
     * @param toUserId    id=2   0;
     * @param transferCash
     */
    @Transactional
    @TimeLog
    @Override
    public void  transfer(Integer fromUserId,Integer  toUserId,Integer transferCash) throws SQLException, IntrospectionException, IllegalAccessException, InvocationTargetException {

        User userFrom = userDao.selectById(fromUserId);
        User userTo = userDao.selectById(toUserId);
        logger.info("转账之前转账用户数据为={}",userFrom);
        logger.info("转账之前被转账用户数据为={}",userTo);
//        TransactionalManager.getInstance().beginTransaction();
        try {
            int up1 = userDao.incrMoney(fromUserId, -transferCash);

            int sum = 1 / 0;
            int up2 = userDao.incrMoney(toUserId, transferCash);
            logger.info("修改记录为up1={},up2:{}",up1,up2);
//            TransactionalManager.getInstance().commit(); ////提交事务
        }finally { //finall执行的时候还没有回滚，直接看数据库是回滚了数据
            userFrom = userDao.selectById(fromUserId);
            userTo = userDao.selectById(toUserId);
            logger.info("finally逻辑-转账之后转账用户数据为="+userFrom);
            logger.info("finally逻辑-转账之后被转账用户数据为="+userTo);
        }



    }

}
